﻿using System;
using System.Text;
using System.Web.UI;
using Microsoft.SharePoint;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Collections.Specialized;
using Microsoft.SharePoint.Security;
using System.Security.Permissions;
using Microsoft.SharePoint.WebControls;

namespace Voodoo.SharePoint.ReadUnreadMarks
{
    //This is the control that renders on SharePoint edit and display forms
    //for the most part the only thing this form does is determine if the
    //user has read it before and if not then trigers the update of the
    //read mark value for this column. there is also a little bit of
    //JavaScript in here to blank out the label and make the display
    //look "empty" if that option is selected
    //the host control is ReadUnreadDataFieldControl.ascx
    public class ReadUnreadFieldControl : Microsoft.SharePoint.WebControls.BaseFieldControl
    {
        #region Declarations
        protected Label _Label = null;
        private ReadUnreadField _ParentField = null;
        private ReadUnreadFieldValue _Value = null;
        #endregion

        #region Constructor
        public ReadUnreadFieldControl(ReadUnreadField parentField)
        {
            _ParentField = parentField;
        }
        #endregion

        #region BaseFieldControl implementation
        protected override string DefaultTemplateName
        {
            get
            {
                return "ReadUnreadFieldControl";
            }
        }

        protected override string DefaultAlternateTemplateName
        {
            get
            {
                return string.Empty;
            }
        }
        public override void Focus()
        {
            EnsureChildControls();
        }

        public override object Value
        {
            get
            {
                return _Value;
            }
            set
            {
                if (value is string)
                {
                    _Value = new ReadUnreadFieldValue(value);
                }
                else
                {
                    if (value is ReadUnreadFieldValue)
                    {
                        _Value = (ReadUnreadFieldValue)value;
                    }
                    else
                    {
                        if (null == value)
                        {
                            _Value = null;
                        }
                        else
                        {
                            throw new InvalidCastException();
                        }
                    }
                }

            }
        }

        #endregion

        #region WebControl implementation
        //per MSDN we need to do most of our heavly lifting
        //in CreateChildControls 
        protected override void CreateChildControls()
        {

            if (null != this.Field)
            {
                base.CreateChildControls();
                _Label = (Label)TemplateContainer.FindControl("labelReadUnreadField");
                //TODO this is always null, dont know why the template is not loaded yet
                if (null == _Label)
                {
                    _Label = new Label();
                    this.Controls.Add(_Label);
                }
                _Label.ID = "lblRUMDF";
                _Label.Text = string.Empty;
                if (null == this.ItemFieldValue) this.ItemFieldValue = new ReadUnreadFieldValue();
                _Value = (ReadUnreadFieldValue)this.ItemFieldValue;

                if (SPControlMode.Display == this.ControlMode)
                {
                    if (Context.User.Identity.IsAuthenticated)
                    {
                        //We dont mark folder items by reading them
                        if (null == this.ListItem.Folder)
                        {
                            //If we are in display mode we need to set the read mark for this user
                            SPUser currentUser = UtilityMethods.EnsureUser(System.Web.HttpContext.Current.User.Identity.Name);
                            try
                            {
                                if (_Value.HasReadMark(currentUser.ID))
                                {
                                    _Label.Text = "-#-";
                                }
                                else
                                {
                                    UtilityMethods.MarkItemAsRead(currentUser, this.ListItem, _ParentField);
                                    _Label.Text = "-*-";
                                }
                            }
                            catch (Exception processingError)
                            {

                                System.Diagnostics.Trace.WriteLine(processingError.Message);
                                _Label.Text = "*?*";
                            }
                        }
                    }

                }

                //In new mode the default value we have configured sets the read mark for this user
                if (SPControlMode.New == this.ControlMode)
                {
                    _Label.Text = "***";
                    //We dont clear the read marks here because the item has not been
                    //saved. we do that in the event handler
                }

            }
        }


        //Not much left except to draw the label 
        protected override void Render(HtmlTextWriter output)
        {
            EnsureChildControls();
            _Label.RenderControl(output);

            string javaScript = HandleListMarkersAndFormVisibilityJavaScript(_Label.ClientID);
            Page.ClientScript.RegisterStartupScript(this.GetType(), "DFA362432302412BA059AD90910AB1D3", javaScript);
           

        }

        //simple function to make the label node invisible using javascript
        private string HandleListMarkersAndFormVisibilityJavaScript(string clientID)
        {
            
            System.Text.StringBuilder returnValue = new System.Text.StringBuilder();
            returnValue.Append("<script type=\"text/javascript\">");
            returnValue.Append("if (window.parent.proxy_markRowRead) {window.parent.proxy_markRowRead(\"readMarkerRow" + this.Item.ID.ToString() + "\");}");
            if (!_ParentField.VisibleOnForm)
            {
                returnValue.Append("var thisRow = document.getElementById(\"");
                returnValue.Append(clientID);
                returnValue.Append("\").parentNode.parentNode; ");
                returnValue.Append("var thisTable = thisRow.parentNode;");
                returnValue.Append("thisTable.removeChild(thisRow);");
            }
            returnValue.Append("</script>");
            return returnValue.ToString();
        }

        #endregion

    }
}
